package com.ruizhong.centercontroll.util;

import android.content.Context;

import org.videolan.libvlc.Media;
import org.videolan.libvlc.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.TextureView;
import android.view.View;


import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.interfaces.IMedia;

import java.util.ArrayList;

/**
 * VLC播放视频工具类
 */
public class VLCPlayer implements MediaPlayer.EventListener {

    private LibVLC libVLC;
    private MediaPlayer mediaPlayer;

    private int videoWidth = 0;  //视频宽度
    private int videoHeight = 0; //视频高度

    private Integer index;

    public VLCPlayer(Context context) {
        ArrayList<String> options = new ArrayList<>();
        options.add("--no-drop-late-frames"); //防止掉帧
        options.add("--no-skip-frames"); //防止掉帧
        options.add("--network-caching=1000");
        options.add("--rtsp-frame-buffer-size=2000000");
        options.add("--rtsp-tcp");//强制使用TCP方式
        options.add("--avcodec-hw=any"); //尝试使用硬件加速
        options.add("--live-caching=0");//缓冲时长
        options.add("--preferred-resolution=-1");
        options.add(" --rtsp-timeout=5");


        libVLC = new LibVLC(context, options);
        mediaPlayer = new MediaPlayer(libVLC);
        mediaPlayer.setEventListener(this);
    }

    /**
     * 设置播放视图
     *
     * @param textureView
     */
    public void setVideoSurface(TextureView textureView) {
        mediaPlayer.getVLCVout().setVideoSurface(textureView.getSurfaceTexture());
        mediaPlayer.getVLCVout().setWindowSize(textureView.getWidth(), textureView.getHeight());
        textureView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom,
                                       int oldLeft, int oldTop, int oldRight, int oldBottom) {
                // 获取新的宽度和高度
                int newWidth = right - left;
                int newHeight = bottom - top;
                // 设置VLC播放器的宽高参数
                mediaPlayer.getVLCVout().setWindowSize(newWidth, newHeight);
            }
        });

        mediaPlayer.getVLCVout().attachViews();

    }

    /**
     * 设置播放地址
     *
     * @param url
     */
    public void setDataSource(String url) {
        try {
            Media media = new Media(libVLC, Uri.parse(url));
            mediaPlayer.setMedia(media);
        } catch (Exception e) {
            Log.e("VLCPlayer", e.getMessage(), e);
        }
    }

    public void setIndex(Integer index){
        this.index = index;
    }
    /**
     * 播放
     */
    public void play() {
        if (mediaPlayer == null) {
            return;
        }
        mediaPlayer.play();
    }

    /**
     * 暂停
     */
    public void pause() {
        if (mediaPlayer == null) {
            return;
        }
        mediaPlayer.pause();
    }

    /**
     * 停止播放
     */
    public void stop() {
        if (mediaPlayer == null) {
            return;
        }
        mediaPlayer.stop();
    }


    /**
     * 释放资源
     */
    public void release() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
        if (libVLC != null) {
            libVLC.release();
        }
    }


    @Override
    public void onEvent(MediaPlayer.Event event) {
        try {
            switch (event.type) {
                case MediaPlayer.Event.Buffering:
                    // 处理缓冲事件
                    if (callback != null) {
                        callback.onBuffering(event.getBuffering(),index);
                    }
                    break;
                case MediaPlayer.Event.EndReached:
                    // 处理播放结束事件
                    if (callback != null) {
                        callback.onEndReached(index);
                    }
                    break;
                case MediaPlayer.Event.EncounteredError:
                    // 处理播放错误事件
                    if (callback != null) {
                        callback.onError(index);
                    }
                    break;
                case MediaPlayer.Event.TimeChanged:
                    // 处理播放进度变化事件
                    if (callback != null) {
                        callback.onTimeChanged(event.getTimeChanged());
                    }
                    break;
                case MediaPlayer.Event.PositionChanged:
                    // 处理播放位置变化事件
                    if (callback != null) {
                        callback.onPositionChanged(event.getPositionChanged());
                    }
                    break;
                case MediaPlayer.Event.Vout:
                    //在视频开始播放之前，视频的宽度和高度可能还没有被确定，因此我们需要在MediaPlayer.Event.Vout事件发生后才能获取到正确的宽度和高度
                    IMedia.VideoTrack vtrack = (IMedia.VideoTrack) mediaPlayer.getSelectedTrack(Media.Track.Type.Video);
                    videoWidth = vtrack.width;
                    videoHeight = vtrack.height;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private VLCPlayerCallback callback;

    public void setCallback(VLCPlayerCallback callback) {
        this.callback = callback;
    }

    public interface VLCPlayerCallback {
        void onBuffering(float bufferPercent,Integer index);

        void onEndReached(Integer index);

        void onError(Integer index);

        void onTimeChanged(long currentTime);

        void onPositionChanged(float position);
    }

}